package com.hyou.cert.config;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.PrivateKey;
import java.util.Date;
import java.util.Enumeration;

import javax.crypto.Cipher;

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

public class PfxDataTest {
    
    public static void main(String[] args) throws Exception {
        
        String password = DataConfig.getTermPwd();
        System.out.println("password : " + password);
        
        char[] pwdCharArr = password.toCharArray();
        
        byte[] pfxData = DataConfig.getTermPfxData();
        System.out.println("pfxData : " + HexBin.encode(pfxData).length());
        
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(new ByteArrayInputStream(pfxData), pwdCharArr);
        
        Enumeration<String> aliases = keyStore.aliases();
        if (!aliases.hasMoreElements()) {
            throw new RuntimeException("no alias found");
        }
        
        String alias = aliases.nextElement();
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, pwdCharArr);
        
        String data = "test string";
        long timestamp = new Date().getTime();
        String signHex = sign(data.getBytes(StandardCharsets.UTF_8), timestamp, privateKey);
        
        System.out.println("signHex : " + signHex);
        System.out.println("signHex : " + signHex.length());
        
    }
    
    public static String sign(byte [] data, long timestamp, PrivateKey key) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(data);
        if(timestamp > 0){
            md.update(EncodeUtil.toBE(timestamp));
        }
        
        byte[] hash = md.digest();
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(hash);
        return HexBin.encode(encrypted);
    }
    
}
